package pooky.server;

import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import com.google.appengine.api.datastore.KeyFactory;


public class Utility {

	private static final PersistenceManagerFactory PMF = JDOHelper.getPersistenceManagerFactory("transactions-optional");
	
	// Thanks to Saqib Ali
	public static boolean doesEntityExist(Class entityClass, String id) {
		  PersistenceManager pm = null;
		  try {
			  pm = PMF.getPersistenceManager();
			  String idKeyString =  KeyFactory.createKeyString(entityClass.getSimpleName(), id);
			  Query q = pm.newQuery("select location from " + entityClass.getName() + " where location == '" + idKeyString + "'");
			  List<String> keys = (List<String>)q.execute();
			  return keys.size()  > 0;
		  } catch (Exception e) {
			  throw new RuntimeException(e);
		  } finally {
			  if (pm != null) pm.close();
		  }
	  }
	
	public static PersistenceManager getPersistenceManager() {
	    return PMF.getPersistenceManager();
	  }
}
